package com.example.demo4.servlet;

import com.example.demo4.Bean.Notice;
import com.example.demo4.dao.NoticeDao;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

@WebServlet("/noticeEdit.jsp")
public class NoticeEditServlet extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{
        req.setCharacterEncoding("UTF-8");
        HttpSession session = req.getSession();
        String User = (String)session.getAttribute("user");
        if (User == null || User.equals("")) {
            resp.sendRedirect("Login.jsp");
            return;
        }
//        int noticeId = Integer.parseInt(req.getParameter("NoticeId"));
        int noticeId = Integer.parseInt(req.getParameter("noticeId"));
        String title = req.getParameter("upd_NoticeTitle");
        String content = req.getParameter("upd_NoticeContent");
        Notice noticeBean = new Notice();
        noticeBean.setNoticeid(noticeId);
        noticeBean.setNoticetitle(title);
        noticeBean.setNoticecontent(content);
        noticeBean.setNoticetime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        noticeBean.setAdminname("admin");// todo 更换为登录的管理员名称
        // 添加
        NoticeDao noticeDao = new NoticeDao();
        int result = noticeDao.updateNotice(noticeBean); // 返回受影响的行
        if(result>0){
            resp.sendRedirect("notice.jsp");
        }else{ // 失败跳转错误页面 显示错误信息 并回到指定页面
            req.setAttribute("msg","添加失败");
            req.setAttribute("url","notice.jsp");// 提示信息后返回的页面
            req.getRequestDispatcher("WEB-INF/error.jsp").forward(req,resp);
        }
    }
}

